<?php


namespace App\MessageHandler;


use App\Entity\Page;
use App\Entity\Setting;
use App\Entity\Subscribe;
use App\Message\SubscribePage;
use App\Utils\Helper\GetterHelper;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class SubscribePageHandler implements MessageHandlerInterface {
    private $logger;
    private $mailer;
    private $container;

    public function __construct (LoggerInterface $logger, MailerInterface $mailer, ContainerInterface $container) {
        $this->logger = $logger;
        $this->mailer = $mailer;
        $this->container = $container;
    }

    public function __invoke (SubscribePage $subscribePage) {
        $page = GetterHelper::getEntityManager()->getRepository(Page::class)->find($subscribePage->getPageId());
        $setting = GetterHelper::getEntityManager()->getRepository(Setting::class)->getCurrentSetting();

        if (!$setting->getIsSubscribe()) {
            $this->logger->notice('未开启邮件订阅功能');
            return;
        }

        if (!is_object($page)) {
            $this->logger->error('订阅邮件发送失败：未找到对应文章，文章ID '.$subscribePage->getPageId());
            return;
        }

        if ($page->getStatus() != 1) {
            $this->logger->warning('订阅邮件：当前文章未发布，文章ID '.$subscribePage->getPageId());
            return;
        }

        $subscribes = GetterHelper::getEntityManager()->getRepository(Subscribe::class)->getAllEmail();
        if ($subscribes) {
            foreach ($subscribes as $subscribe) {
                $email = (new TemplatedEmail())
                    ->from($this->container->getParameter('app.smtp.email'))
                    ->to($subscribe)
                    ->subject('【'.$setting->getSiteName().'】发布了新博文')
                    ->htmlTemplate('backend/public/email.html.twig')
                    ->context([
                        'page_id' => $page->getId(),
                        'title'   => $page->getTitle(),
                        'summary' => $page->getSummary(),
                    ]);
                $this->mailer->send($email);
            }
        }
    }
}